import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { TypeDto } from './dto/type.dto';
import { Type } from './type.entity';

@Injectable()
export class TypeService {
    constructor(
        @InjectRepository(Type)
        private readonly typeRepo: Repository<Type>,
    ){}

    // 新增文章类型
    async saveType(newType: TypeDto){
        return await this.typeRepo.save(newType)
    }

    // 查询所有文章类型
    async getAllType(){
        return await this.typeRepo.find()
    }

    // 根据id查询文章类型
    async getTypeById(id: number){
        return await this.typeRepo.findOne(id)
    }

    // 更新文章类型
    async updateTypeById(id: number, updatedType: TypeDto){
        return await this.typeRepo.update(id, updatedType)
    }

    // 删除文章类型
    async deleteTypeById(id: number){
        return await this.typeRepo.delete(id)
    }

    // 分页返回数据 包括 totalnum 、pagenum、types
    async getTypeByQuery(query, pagenum, pagesize){
        // 总数
        // let total = await this.typeRepo
        // .createQueryBuilder('type')
        // .getCount()


        let keyWord = { key: `%${query}%` }
        let sql1 = query ? 'type.name like :key' : "1=1"

        let types = await this.typeRepo
        .createQueryBuilder('type')
        //.where("type.name like :name", {name: `%${query}%`})
        .where(sql1, keyWord)
        .skip((pagenum - 1) * pagesize)
        .take(pagesize)
        .getManyAndCount()
        
       let total = types[1]
        // 整理结果
        let result = {
            total: total,
            pagenum: pagenum,
            types: types[0]
        }

        return result
    }

}
